package com.cloudcentral.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cloudcentral.entity.RadioDevice;
import com.google.common.base.CaseFormat;

import java.lang.reflect.Field;

/**
 * <p>
 * 台站设备信息上报记录表 Mapper 接口
 * </p>
 *
 * @author Administrator
 * @since 2023-11-22
 */
public interface RadioDeviceMapper extends BaseMapper<RadioDevice> {
  private Object selectColumn(Integer radioId, String column) throws Exception {
    column = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, column);
    QueryWrapper<RadioDevice> queryWrapper = new QueryWrapper<>();
    queryWrapper.select(column).isNotNull(column).eq("radio_id", radioId).orderByDesc("report_time").last("limit 1");
    column = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, column);
    RadioDevice radioDevice = selectOne(queryWrapper);
    Field field = RadioDevice.class.getDeclaredField(column);
    field.setAccessible(true);
    Object value = field.get(radioDevice);
    field.setAccessible(false);
    return value;
  }

  default RadioDevice selectDeviceInfo(Integer radioId) throws Exception {
    QueryWrapper<RadioDevice> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("radio_id", radioId).orderByDesc("report_time").last("limit 1");
    RadioDevice radioDevice = selectOne(queryWrapper);
    if (radioDevice != null) {
      for (Field field : RadioDevice.class.getDeclaredFields()) {
        field.setAccessible(true);
        Object fieldValue = field.get(radioDevice);
        if (fieldValue == null) field.set(radioDevice, selectColumn(radioId, field.getName()));
        field.setAccessible(false);
      }
    }
    return radioDevice;
  }
}
